package com.csair.platform.cit.service.biz.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csair.invoice.common.base.util.BeanUtils;
import com.csair.invoice.common.base.util.StringUtil;
import com.csair.invoice.common.base.util.collection.CollectionUtil;
import com.csair.invoice.common.base.util.date.DatetimeUtil;
import com.csair.invoice.common.base.util.io.FileUtil;
import com.csair.invoice.common.base.vo.JsonResult;
import com.csair.platform.cit.facade.exception.CitBizException;
import com.csair.platform.cit.facade.model.CitQueryParam;
import com.csair.platform.cit.facade.model.CitSendParam;
import com.csair.platform.cit.facade.model.a200000.declare.JmCzzsYjd2021NsrxxFormVO;
import com.csair.platform.cit.facade.model.a200000.declare.JmCzzsYjd2021QtxxFormVO;
import com.csair.platform.cit.facade.model.a200000.declare.JmCzzsYjd2021SbxxFormVO;
import com.csair.platform.cit.facade.model.a200000.declare.JmCzzsYjd2021YhjmxxVO;
import com.csair.platform.cit.facade.model.a200000.declare.JmCzzsYjd2021yhfbxxFormVO;
import com.csair.platform.cit.facade.model.a202000.declare.FzjgxxGridlbVO;
import com.csair.platform.cit.facade.model.a202000.declare.ZjgxxFormVO;
import com.csair.platform.cit.facade.model.citwgqyGrid.sb.vo.CitWgqyGridFb1SbVo;
import com.csair.platform.cit.facade.model.citwgqyGrid.sb.vo.CitWgqyGridFb2SbVo;
import com.csair.platform.cit.facade.model.citwgqyGrid.sb.vo.CitWgqyGridFb3SbVo;
import com.csair.platform.cit.facade.model.citwgqyGrid.sb.vo.CitWgqyGridFb4SbVo;
import com.csair.platform.cit.service.biz.IA200000Service;
import com.csair.platform.cit.service.biz.IA202000Service;
import com.csair.platform.cit.service.biz.ICitJscgService;
import com.csair.platform.cit.service.biz.ICitZcjszjkcmxbService;
import com.csair.platform.cit.service.biz.IDeclareService;
import com.csair.platform.cit.service.biz.impl.sb.JpathServiceImpl;
import com.csair.platform.cit.service.dao.CitJscgRepository;
import com.csair.platform.cit.service.dao.a200000.CitWgqyGridFb1Repository;
import com.csair.platform.cit.service.dao.a200000.CitWgqyGridFb2Repository;
import com.csair.platform.cit.service.dao.a200000.CitWgqyGridFb3Repository;
import com.csair.platform.cit.service.dao.a200000.CitWgqyGridFb4Repository;
import com.csair.platform.cit.service.dao.a200000.CitWgqyGridRepository;
import com.csair.platform.cit.service.entity.CitDeclareRecord;
import com.csair.platform.cit.service.entity.CitSbbxx;
import com.csair.platform.cit.service.entity.CitWgqyGrid;
import com.csair.platform.cit.service.entity.CitWgqyGridFb1;
import com.csair.platform.cit.service.entity.CitWgqyGridFb2;
import com.csair.platform.cit.service.entity.CitWgqyGridFb3;
import com.csair.platform.cit.service.entity.CitWgqyGridFb4;
import com.csair.platform.cit.service.feignclient.sbcenter.SbqcFeignClient;
import com.csair.platform.cit.service.util.JsonHelper;
import com.csair.platform.gts.sdk.EnterpriseDeclareClient;
import com.csair.platform.sbcenter.facade.model.sbqc.SbqcQueryParam;
import com.csair.platform.usercenter.facade.model.user.UserVo;
import com.google.gson.reflect.TypeToken;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * [企业所得税申报]服务实现类
 * @author ：caoyu
 *
 */
@Slf4j
@Service
public class DeclareServiceImpl extends InitBaseServiceImpl implements IDeclareService {

    /**
     * 主表数据服务
     */
    @Autowired
    IA200000Service a200000Service;

    /**
     * 分配表数据服务
     */
    @Autowired
    IA202000Service a202000Service;

    /**
     * 外国持股企业信息dao
     */
    @Autowired
    CitWgqyGridRepository wgqyGridDao;

    /**
     * 申报清册client， 目前用来获取申报期限
     */
    @Autowired
    private SbqcFeignClient sbqcFeignClient;

    @Autowired
    CitWgqyGridFb1Repository fb1Dao;

    @Autowired
    CitWgqyGridFb2Repository fb2Dao;

    @Autowired
    CitWgqyGridFb3Repository fb3Dao;

    @Autowired
    CitWgqyGridFb4Repository fb4Dao;

    @Autowired
    CitJscgRepository jscgDao;

    @Autowired
    ICitZcjszjkcmxbService czsService;

    @Autowired
    ICitJscgService cjscgService;

    @Autowired
    JpathServiceImpl jpathService;
    /**
     * 广东电子税务局接口地址
     */
    @Value("${dzswj.url}")
    private String serverUrl;


    private void formatJpath(String data){
    	log.info("打印格式化后的jpath：");
        String [] str = data.split(",");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length; i++) {
        	sb.append(str[i]).append(",").append("\r\n");
        }
        FileUtil.writeStringToFile(sb.toString(), "/Users/liaoxiaojin/logs/日志.log");
    }

    @Override
    public void send(CitSendParam param, UserVo user) {
        CitQueryParam queryParam = new CitQueryParam();
        BeanUtils.copyProperties(param, queryParam);
        //申报前，先调一下期初接口
        this.getInitJsonData(queryParam, user);
        CitDeclareRecord declareRecord = this.queryDeclareRecord(param);
        if (declareRecord != null && "申报成功".equals(declareRecord.getStatus())) {
            //throw new CitBizException(CitBizException.FORBID_REPEATED_DECLARE, "当前税号本属期企业所得税已申报成功，不要重复申报");
        }
//        JSONObject json = this.getRequestJson(param, user);
//        log.info("申报的请求报文[json]为：" + json);
        
        // String wbcsh = this.parseJPathData(param.getNsrsbh(), param.getSkssqq(), param.getSkssqz(), json);
        //log.info("申报的请求报文[Jpath格式]为：" + JSON.toJSONString(wbcsh));
       
        String wbcsh = jpathService.getJpath(queryParam);
        formatJpath(wbcsh);
        Map<String, String> map = this.getParams(queryParam, user);
        
        String returnStr = this.submitAndSend(user, wbcsh, map);
        JSONObject resultJson = JSON.parseObject(returnStr);
        String bodyStr = resultJson.getString("body");
        JSONObject body1 = JSON.parseObject(bodyStr);
        // 连body都没有,就直接弹报文
        if (body1 == null) {
            throw new CitBizException(CitBizException.SEND_ERROR, returnStr);
        }
        log.info("body:" + JSON.toJSONString(body1));
        if (declareRecord == null) {
            declareRecord = new CitDeclareRecord();
            declareRecord.setNsrsbh(param.getNsrsbh());
            declareRecord.setSwjgmc(map.get("zgswjgmc")); //主管税务机关名称
            declareRecord.setTaxName("企业所得税");
            declareRecord.setSbzl("10104"); //申报种类
            declareRecord.setSkssqq(param.getSkssqq());
            declareRecord.setSkssqz(param.getSkssqz());
            declareRecord.setCreateTime(new Date());
            declareRecord.setCreateBy(user == null ? null: user.getAccount());
        }
        declareRecord.setSendTime(new Date());
        Integer rtnCode = body1.getInteger("code");
        if (rtnCode == 0) { //申报受理成功
            String rtnMessage = body1.getString("msg");
            String jmsbId = body1.getString("jmsbId"); //请求流水号
            log.info("企业所得税申报流水号jmsbId：" + jmsbId);
            declareRecord.setStatus("申报中");
            declareRecord.setFkxx(rtnMessage);
            declareRecord.setJylsh(jmsbId);
        } else if (rtnCode == 9) { //申报失败
            String rtnMessage = body1.getString("msg");
            declareRecord.setStatus("申报失败");
            declareRecord.setFkxx(rtnMessage);
            declareRecord.setJylsh("");
        }
        declareRecord.setFkdm("");
        declareRecord.setJgfkxx("");
        declareRecord.setUpdateTime(null);
        declareRecord.setTaxAmount(new BigDecimal(getSbse(queryParam))); //申报税额 = 主表数据24行的实际应补（退）所得税额（sjybtsdseBq）
        declareRecordDao.save(declareRecord);
        log.info("企业所得税申报受理记录保存成功");
    }

    /**
     * 通过4.2.1接口进行企业所得税申报
     * @param user 当前用户
     * @param wbcsh 接口申报数据jpath格式报文
     * @param map 调用接口需要相关请求参数
     * @return 企业所得税申报返回报文[json]
     */
    @SneakyThrows
    private String submitAndSend(UserVo user, String wbcsh, Map<String, String> map) {
        EnterpriseDeclareClient client = new EnterpriseDeclareClient(serverUrl);
        String ssoSessionId = map.get("ssoSessionId");
        //String nsrsbh = param.getNsrsbh();
        String nsrsbh = map.get("taxNo");
        String djxh = map.get("djxh");
        String sssqq = map.get("skssqq");
        String sssqz = map.get("skssqz");
        String zjlx = map.get("zjlx");
        String zjhm = map.get("zjhm");
        String yhm = map.get("yhm");
        String xm = map.get("xm");
        String sjhm = map.get("sjhm");
        String userInfo = "{\"zjlx\":\"" + zjlx + "\",\"zjhm\":\"" + zjhm + "\",\"xm\":\"" + xm + "\",\"sjhm\":\"" + sjhm + "\"}";
        String zgswjgdm = map.get("zgswjgdm");
        if(StringUtil.isEmpty(zgswjgdm) && "91440000100017600N".equals(nsrsbh)) {
            zgswjgdm = "14401110400";
        }
        if(StringUtil.isEmpty(zgswjgdm) && "91440000100005896P".equals(nsrsbh)) {
            zgswjgdm = "14401930004";
        }
        if (StringUtil.isEmpty(zgswjgdm)) {
            throw new CitBizException(CitBizException.ZGSWJGDM_NOT_FOUND, "主管税务机关代码不能为空");
        }
        //调申报清册接口获取申报期限
        String sbqx = this.getSbqx(sssqz, yhm);
        String jsonStr = client.send(ssoSessionId, djxh, nsrsbh, zgswjgdm, sssqq, sssqz, sbqx, userInfo, wbcsh);
        log.info("企业所得税申报返回报文：" + jsonStr);
        return jsonStr;
    }

    /**
     * 调用申报清册接口获取企业所得税当前属期的申报期限
     * @param sssqz 申报属期止
     * @param yhm 用户名
     * @return 申报期限
     */
    private String getSbqx(String sssqz, String yhm) {
        SbqcQueryParam param = new SbqcQueryParam();
        //日期转换： 2021-09-30 => 202110
        Date dateEndMonthFirstDay = DatetimeUtil.strToDate(sssqz.substring(0, 7) + "-01", DatetimeUtil.DATE_FORMAT);
        String nextMonthFirstDayStr = DatetimeUtil.dateToStr(DatetimeUtil.addMonth(dateEndMonthFirstDay, 1), DatetimeUtil.DATE_FORMAT);
        String yearMonth = nextMonthFirstDayStr.substring(0, 7).replace("-", "");
        param.setYearMonth(yearMonth);
        param.setUserName(yhm);
        param.setAutoLogin(false);
        JsonResult<JSONObject> result = sbqcFeignClient.getSbqcData(param);
        List<JSONObject> list = result.getData();
        if (CollectionUtil.isNotEmpty(list)) {
            for (JSONObject data : list) {
                String zsxmMc = data.getString("zsxmMc");
                if (zsxmMc.contains("企业所得税")) {
                    return data.getString("sbqx");
                }
            }
        }
        return "";
    }

    
    public String getSbse(CitQueryParam queryParam){
        CitSbbxx citSbbxx = a200000Service.querySbbxx(queryParam.getNsrsbh(),queryParam.getSkssqq(),queryParam.getSkssqz()).get(0);
        return citSbbxx.getSjybtsdseBq();
    }

    /**
     * 将JSON格式转换为JPath格式字符串
     * @param nsrsbh 纳税人识别号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @param json JSONObject对象
     * @return JPath格式字符串
     */
    public String parseJPathData(String nsrsbh, String skssqq, String skssqz, JSONObject json) {
        StringBuffer sb = new StringBuffer("{");
        String htStr = json.getString("ht_");
        JSONObject dataHt = JSON.parseObject(htStr);
        String ywbwStr = dataHt.getString("ywbw");
        JSONObject dataYwbw = JSON.parseObject(ywbwStr);
        String a200000YwbdStr = dataYwbw.getString("A200000Ywbd");
        JSONObject dataA200000Ywbd = JSON.parseObject(a200000YwbdStr);
        //1.1.主表数据-纳税人信息
        String nsrxx = this.parseJPathInfoData(dataA200000Ywbd, "nsrxxForm", "ht_.ywbw.A200000Ywbd.nsrxx", false);
        sb.append(nsrxx);
        //1.2.主表数据-申报表信息
        String sbbxx = this.parseJPathInfoData(dataA200000Ywbd, "sbbxxForm", "ht_.ywbw.A200000Ywbd.sbxx", false);
        sb.append(sbbxx);
        //1.3.主表数据-其他信息
        String qtxx = this.parseJPathInfoData(dataA200000Ywbd, "nsrqtxxForm", "ht_.ywbw.A200000Ywbd.qtxx", false);
        sb.append(qtxx);
        //1.4.主表数据-优惠减免信息
        //7.x
        String mssrGridStr = dataA200000Ywbd.getString("mssrGrid");
        JSONObject dataMssrGrid = JSON.parseObject(mssrGridStr);
        String mssrxx = this.parseJPathInfoData(dataMssrGrid, "mssrGridlb", "ht_.ywbw.A200000Ywbd.mssrGrid.mssrGridlb", true);
        sb.append(mssrxx);
        //8.x
        String sdjmGridStr = dataA200000Ywbd.getString("sdjmGrid");
        JSONObject dataSdjmGrid = JSON.parseObject(sdjmGridStr);
        String sdjmxx = this.parseJPathInfoData(dataSdjmGrid, "sdjmGridlb", "ht_.ywbw.A200000Ywbd.sdjmGrid.sdjmGridlb", true);
        sb.append(sdjmxx);
        //13.x
        String jmsdGridStr = dataA200000Ywbd.getString("jmsdGrid");
        JSONObject dataJmsdGrid = JSON.parseObject(jmsdGridStr);
        String jmsdxx = this.parseJPathInfoData(dataJmsdGrid, "jmsdGridlb", "ht_.ywbw.A200000Ywbd.jmsdGrid.jmsdGridlb", true);
        sb.append(jmsdxx);
        //1.5.主表数据-外国持股企业信息
        String wgqyxx = this.getWgqyData(nsrsbh, skssqq, skssqz);
        sb.append(wgqyxx);
        //1.6
        //1.7 技术成果投资入股企业所得税递延纳税备案表
       // String dynsbaGridlb = getJscgJpath(nsrsbh, skssqq, skssqz);
       // sb.append(dynsbaGridlb);
        String czsGrid = czsService.getJpath(nsrsbh,skssqq,skssqz);
        sb.append(czsGrid);

        if ("91440000100017600N".equals(nsrsbh)) { //股份才有分配表数据
            //2.1.分配表数据-总机构信息
            String a202000YwbdStr = dataYwbw.getString("A202000Ywbd");
            JSONObject dataA202000Ywbd = JSON.parseObject(a202000YwbdStr);
            String zjgxx = this.parseJPathInfoData(dataA202000Ywbd, "zjgxxForm", "ht_.ywbw.A202000Ywbd.zjgxxForm", false);
            sb.append(zjgxx);
            //2.2.分配表数据-分支机构信息
            String fzjgxxGridStr = dataA202000Ywbd.getString("fzjgxxGrid");
            JSONObject dataFzjgxxGrid = JSON.parseObject(fzjgxxGridStr);
            String fzjgxx = this.parseJPathInfoData(dataFzjgxxGrid, "fzjgxxGridlb", "ht_.ywbw.A202000Ywbd.fzjgxxGrid.fzjgxxGridlb", true);
            sb.append(fzjgxx);
        }
        String result = sb.toString();
        result = result.substring(0, result.length() - 1) + "}";
        return result;
    }
    /**
     * 获取外国持股企业信息数据
     * @param nsrsbh 纳税人识别号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return 外国持股企业信息数据[JPath格式]
     */
    public String getWgqyData(String nsrsbh, String skssqq, String skssqz) {
        StringBuffer sb = new StringBuffer();
        CitWgqyGrid query = new CitWgqyGrid();
        query.setNsrsbh(nsrsbh);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitWgqyGrid> example = Example.of(query);
        List<CitWgqyGrid> list = wgqyGridDao.findAll(example);


        if (CollectionUtil.isNotEmpty(list)) {
            String postFix = "kz_.temp.cgwgqyxxbgbVO";
            String midFix = "wgqyxxForm";
            for (int i = 0 ; i < list.size() ; i++) {
                CitWgqyGrid vo = list.get(i);

//                sb.append("\"" + postFix + "[" + i + "].dsxxGrid\": [],");
//                sb.append("\"" + postFix + "[" + i + "].sggfxxGrid\": [],");
//                sb.append("\"" + postFix + "[" + i + "].czgfxxGrid\": [],");
//                sb.append("\"" + postFix + "[" + i + "].gdxxGrid\": [],");
                Map<String, Object> map = BeanUtils.object2Map(vo);
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    String key = entry.getKey();
                    if ("nsrsbh".equals(key) || "nsrmc".equals(key) || "id".equals(key) || "skssqq".equals(key) || "skssqz".equals(key)) {
                        continue;
                    }
                    if("mxxh".equals(key)) {
                        sb.append("\"" + postFix + "[" + i + "]." + midFix + "." + key + "\": \""  + "\",");
                    } else {
                        Object valueObj = entry.getValue();
                        sb.append("\"" + postFix + "[" + i + "]." + midFix + "." + key + "\": \"" + valueObj.toString() + "\",");
                    }
                }
                getfb1(vo.getId(),i,sb,postFix);
                getfb2(vo.getId(),i,sb,postFix);
                getfb3(vo.getId(),i,sb,postFix);
                getfb4(vo.getId(),i,sb,postFix);

            }
        }
        log.info("外国企业参股："+ sb.toString());
        return sb.toString();
    }

    /**
     * 获取外国企业 附表1数据
     * @param parentId 父类id
     * @param index 数据格式下表
     * @param sb 拼接字符串
     * @param postFix 前缀 固定值，写死
     * @param
     */
    private void getfb1(Long parentId, int index, StringBuffer sb,String postFix) {
        String suffix = "gdxxGrid.gdxxGridlb";
        List<CitWgqyGridFb1> fb1Data= fb1Dao.queryByParentId(parentId);

        if(CollectionUtil.isEmpty(fb1Data)){
            return;
        }

        List<CitWgqyGridFb1SbVo> sb1 = JsonHelper.from(fb1Data,new TypeToken<List<CitWgqyGridFb1SbVo>>() {}.getType());

        for (int i = 0; i < sb1.size(); i++) {
            CitWgqyGridFb1 fb1 = fb1Data.get(i);
            Map<String, Object> fb1Map = BeanUtils.object2Map(fb1);
            for (Map.Entry<String, Object> entry : fb1Map.entrySet()){
                sb.append("\"" + postFix + "[" + index + "]."+suffix +"["+i+"]."+ entry.getKey() +"\":\"" + entry.getValue() + "\",");
            }
        }
    }

    /**
     * 获取外国企业 附表1数据
     * @param parentId 父类id
     * @param index 数据格式下表
     * @param sb 拼接字符串
     * @param postFix 前缀 固定值，写死
     * @param
     */
    private void getfb2(Long parentId, int index, StringBuffer sb,String postFix) {
        String suffix = "dsxxGrid.dsxxGridlb";
        List<CitWgqyGridFb2> fb2Data= fb2Dao.queryByParentId(parentId);
        if(CollectionUtil.isEmpty(fb2Data)){
            return;
        }

        List<CitWgqyGridFb2SbVo> sb2 = JsonHelper.from(fb2Data,new TypeToken<List<CitWgqyGridFb2SbVo>>() {}.getType());

        for (int i = 0; i < sb2.size(); i++) {
            CitWgqyGridFb2 fb2 = fb2Data.get(i);
            Map<String, Object> fb1Map = BeanUtils.object2Map(fb2);
            for (Map.Entry<String, Object> entry : fb1Map.entrySet()){
                sb.append("\"" + postFix + "[" + index + "]."+suffix +"["+i+"]."+ entry.getKey() +"\":\"" + entry.getValue() + "\",");
            }
        }
    }

    /**
     * 获取外国企业 附表1数据
     * @param parentId 父类id
     * @param index 数据格式下表
     * @param sb 拼接字符串
     * @param postFix 前缀 固定值，写死
     * @param
     */
    private void getfb3(Long parentId, int index, StringBuffer sb,String postFix) {
        String suffix = "sggfxxGrid.sggfxxGridlb";
        List<CitWgqyGridFb3> fb3Data= fb3Dao.queryByParentId(parentId);
        if(CollectionUtil.isEmpty(fb3Data)){
            return;
        }

        List<CitWgqyGridFb3SbVo> sb3 = JsonHelper.from(fb3Data,new TypeToken<List<CitWgqyGridFb3SbVo>>() {}.getType());

        for (int i = 0; i < sb3.size(); i++) {
            CitWgqyGridFb3 fb3 = fb3Data.get(i);
            Map<String, Object> fb1Map = BeanUtils.object2Map(fb3);
            for (Map.Entry<String, Object> entry : fb1Map.entrySet()){
                sb.append("\"" + postFix + "[" + index + "]."+suffix +"["+i+"]."+ entry.getKey() +"\":\"" + entry.getValue() + "\",");
            }
        }
    }

    /**
     * 获取外国企业 附表1数据
     * @param parentId 父类id
     * @param index 数据格式下表
     * @param sb 拼接字符串
     * @param postFix 前缀 固定值，写死
     * @param
     */
    private void getfb4(Long parentId, int index, StringBuffer sb,String postFix) {
        String suffix = "czgfxxGrid.czgfxxGridlb";
        List<CitWgqyGridFb4> fb4Data= fb4Dao.queryByParentId(parentId);
        if(CollectionUtil.isEmpty(fb4Data)){
            return;
        }

        List<CitWgqyGridFb4SbVo> sb4 = JsonHelper.from(fb4Data,new TypeToken<List<CitWgqyGridFb4SbVo>>() {}.getType());

        for (int i = 0; i < sb4.size(); i++) {
            CitWgqyGridFb4 fb4 = fb4Data.get(i);
            Map<String, Object> fb1Map = BeanUtils.object2Map(fb4);
            for (Map.Entry<String, Object> entry : fb1Map.entrySet()){
                sb.append("\"" + postFix + "[" + index + "]."+suffix +"["+i+"]."+ entry.getKey() +"\":\"" + entry.getValue() + "\",");
            }
        }
    }

    /**
     * 解析JPath格式字符串
     * @param json JSONObject对象
     * @param entityName 实体名
     * @param postFix JPath格式前缀
     * @param isArray 是否数组
     * @return JPath格式字符串
     */
    private String parseJPathInfoData(JSONObject json, String entityName, String postFix, boolean isArray) {
        StringBuffer sb = new StringBuffer();
        if (isArray) {
            JSONArray data = json.getJSONArray(entityName);
            for (int i = 0 ; i < data.size() ; i++) {
                JSONObject object = data.getJSONObject(i);
                Map<String, Object> map = BeanUtils.json2Map(object.toJSONString());
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    String key = entry.getKey();
                    Object valueObj = entry.getValue();
                    if (valueObj instanceof String) {
                        sb.append("\"" + postFix + "[" + i + "]." + key + "\": \"" + valueObj.toString() + "\",");
                    } else {
                        sb.append("\"" + postFix + "[" + i + "]." + key + "\": " + valueObj.toString() + ",");
                    }
                }
            }
        } else {
            String jsonStr = json.getString(entityName);
            Map<String, Object> map = BeanUtils.json2Map(jsonStr);
            for (Map.Entry<String, Object> entry : map.entrySet()){
                String key = entry.getKey();
                Object valueObj = entry.getValue();
                if (valueObj instanceof String) {
                    sb.append("\"" + postFix + "." + key + "\": \"" + valueObj.toString() + "\",");
                } else {
                    sb.append("\"" + postFix + "." + key + "\": " + valueObj.toString() + ",");
                }
            }
        }
        return sb.toString();
    }

    /**
     * 获取请求报文
     * @param param 申报参数
     * @param user 当前用户
     * @return 请求报文
     */
    private JSONObject getRequestJson(CitSendParam param, UserVo user) {
        CitQueryParam queryParam = new CitQueryParam();
        BeanUtils.copyProperties(param, queryParam);
        JSONObject jsonA200000Ywbd = new JSONObject();
        //=================1.主表数据=================
        JsonResult<JSONObject> zb = a200000Service.query(queryParam, user, true);
        List<JSONObject> listZb = zb.getData();
        JSONObject dataZb = listZb.get(0);
        //log.info("从数据库获取到的主表数据：" + dataZb.toString());
        //1.1.主表数据-纳税人信息
        String nsrxxStr = dataZb.getString("nsrxx");
        Map<String, Object> mapNsrxx = BeanUtils.json2Map(nsrxxStr);
        JmCzzsYjd2021NsrxxFormVO nsrxxVo = BeanUtils.map2Bean(mapNsrxx, JmCzzsYjd2021NsrxxFormVO.class);
        log.info("1.1.主表数据-纳税人信息：" + nsrxxVo.toString());
        jsonA200000Ywbd.put("nsrxxForm", nsrxxVo);
        //1.2.主表数据-申报表信息
        String sbbxxStr = dataZb.getString("sbbxx");
        Map<String, Object> mapSbbxx = BeanUtils.json2Map(sbbxxStr);
        JmCzzsYjd2021SbxxFormVO sbbxxVo = BeanUtils.map2Bean(mapSbbxx, JmCzzsYjd2021SbxxFormVO.class);
        String yhfbxxStr = dataZb.getString("yhfbxx");
        log.info("获取到的优惠附表数据1：" + yhfbxxStr);
        Map<String, Object> mapYhfbxx = BeanUtils.json2Map(yhfbxxStr);
        JmCzzsYjd2021yhfbxxFormVO yhfbxxVo = BeanUtils.map2Bean(mapYhfbxx, JmCzzsYjd2021yhfbxxFormVO.class);
        log.info("获取到的优惠附表数据2：" + yhfbxxVo.toString());
        BeanUtils.copyProperties(yhfbxxVo, sbbxxVo);
        log.info("获取到的优惠附表数据3：" + sbbxxVo.toString());
        sbbxxVo.setSfsyxxwlqy("N");
        sbbxxVo.setSfkjxzxqy("");
        sbbxxVo.setSfgxjsqy("");
        sbbxxVo.setSffsjsrgdynssx("");
        sbbxxVo.setQmcyrs(BigDecimal.ZERO);
        sbbxxVo.setQccyrs(BigDecimal.ZERO);
        sbbxxVo.setQczcze(BigDecimal.ZERO);
        sbbxxVo.setQmzcze(BigDecimal.ZERO);
        sbbxxVo.setGjxzhjzhy("N");
        log.info("1.2.主表数据-申报表信息：" + sbbxxVo.toString());
        jsonA200000Ywbd.put("sbbxxForm", sbbxxVo);
        //1.3.主表数据-其他信息
        String qtxxStr = dataZb.getString("qtxx");
        Map<String, Object> mapQtxx = BeanUtils.json2Map(qtxxStr);
        JmCzzsYjd2021QtxxFormVO qtxxVo = BeanUtils.map2Bean(mapQtxx, JmCzzsYjd2021QtxxFormVO.class);
        log.info("1.3.主表数据-其他信息：" + qtxxVo.toString());
        jsonA200000Ywbd.put("nsrqtxxForm", qtxxVo);
        //1.4.主表数据-优惠减免数据
        //7.x
        JSONArray dataMssr = dataZb.getJSONArray("mssrxx");
        List<JmCzzsYjd2021YhjmxxVO> mssrxxList = new ArrayList<>();
        for (int i = 0 ; i < dataMssr.size() ; i++) {
            JSONObject object = dataMssr.getJSONObject(i);
            Map<String, Object> mapMssrxx = BeanUtils.json2Map(object.toJSONString());
            JmCzzsYjd2021YhjmxxVO mssrxxVo = BeanUtils.map2Bean(mapMssrxx, JmCzzsYjd2021YhjmxxVO.class);
            mssrxxList.add(mssrxxVo);
        }
        JSONObject jsonMssrGrid = new JSONObject();
        jsonMssrGrid.put("mssrGridlb", mssrxxList);
        jsonA200000Ywbd.put("mssrGrid", jsonMssrGrid);
        log.info("1.4.主表数据-优惠减免数据(7.x)：" + mssrxxList.toString());
        //8.x
        JSONArray dataSdjm = dataZb.getJSONArray("sdjmxx");
        List<JmCzzsYjd2021YhjmxxVO> sdjmxxList = new ArrayList<>();
        for (int i = 0 ; i < dataSdjm.size() ; i++) {
            JSONObject object = dataSdjm.getJSONObject(i);
            Map<String, Object> mapSdjmxx = BeanUtils.json2Map(object.toJSONString());
            JmCzzsYjd2021YhjmxxVO sdjmxxVo = BeanUtils.map2Bean(mapSdjmxx, JmCzzsYjd2021YhjmxxVO.class);
            sdjmxxList.add(sdjmxxVo);
        }
        JSONObject jsonSdjmGrid = new JSONObject();
        jsonSdjmGrid.put("sdjmGridlb", sdjmxxList);
        jsonA200000Ywbd.put("sdjmGrid", jsonSdjmGrid);
        log.info("1.4.主表数据-优惠减免数据(8.x)：" + sdjmxxList.toString());
        //13.x
        JSONArray dataJmsd = dataZb.getJSONArray("jmsdxx");
        List<JmCzzsYjd2021YhjmxxVO> jmsdxxList = new ArrayList<>();
        for (int i = 0 ; i < dataJmsd.size() ; i++) {
            JSONObject object = dataJmsd.getJSONObject(i);
            Map<String, Object> mapJmsdxx = BeanUtils.json2Map(object.toJSONString());
            JmCzzsYjd2021YhjmxxVO jmsdxxVo = BeanUtils.map2Bean(mapJmsdxx, JmCzzsYjd2021YhjmxxVO.class);
            jmsdxxList.add(jmsdxxVo);
        }
        JSONObject jsonJmsdGrid = new JSONObject();
        jsonJmsdGrid.put("jmsdGridlb", jmsdxxList);
        jsonA200000Ywbd.put("jmsdGrid", jsonJmsdGrid);
        log.info("1.4.主表数据-优惠减免数据(13.x)：" + jmsdxxList.toString());
        JSONObject jsonYwbw = new JSONObject();
        jsonYwbw.put("A200000Ywbd", jsonA200000Ywbd);
        if ("91440000100017600N".equals(param.getNsrsbh())) { //股份才有分配表，集团没有
            //=================2.分配表数据=================
            JSONObject jsonA202000Ywbd = new JSONObject();
            JsonResult<JSONObject> fpb = a202000Service.query(queryParam, user, true);
            List<JSONObject> listFpb = fpb.getData();
            JSONObject dataFpb = listFpb.get(0);
            //log.info("从数据库获取到的分配表数据：" + dataFpb.toString());
            //2.1.分配表数据-总机构信息
            String zjgxxStr = dataFpb.getString("zjgxx");
            Map<String, Object> mapZjgxx = BeanUtils.json2Map(zjgxxStr);
            ZjgxxFormVO zjgxxVo = BeanUtils.map2Bean(mapZjgxx, ZjgxxFormVO.class);
            log.info("2.1.分配表数据-总机构信息：" + zjgxxVo.toString());
            jsonA202000Ywbd.put("zjgxxForm", zjgxxVo);
            JSONArray dataFzjg = dataFpb.getJSONArray("fzjgxx");
            List<FzjgxxGridlbVO> fzjgxxVo = new ArrayList<>();
            for (int i = 0 ; i < dataFzjg.size() ; i++) {
                JSONObject object = dataFzjg.getJSONObject(i);
                Map<String, Object> mapFzjgxx = BeanUtils.json2Map(object.toJSONString());
                FzjgxxGridlbVO fzjgxx = BeanUtils.map2Bean(mapFzjgxx, FzjgxxGridlbVO.class);
                fzjgxxVo.add(fzjgxx);
            }
            log.info("2.2.分配表数据-分支机构信息：" + fzjgxxVo.toString());
            JSONObject jsonFzjgxxGrid = new JSONObject();
            jsonFzjgxxGrid.put("fzjgxxGridlb", fzjgxxVo);
            jsonA202000Ywbd.put("fzjgxxGrid", jsonFzjgxxGrid);
            jsonYwbw.put("A202000Ywbd", jsonA202000Ywbd);
        }
        JSONObject jsonData = new JSONObject();
        jsonData.put("ywbw", jsonYwbw);
        JSONObject jsonht = new JSONObject();
        jsonht.put("ht_", jsonData);
        return jsonht;
    }

}
